package com.weiz.thread.scheduledexecutor;
import java.util.concurrent.*;
public class ScheduledExecutorServiceBestPractice {
    public static void main(String[] args) {
        // 自定义核心线程数
        int corePoolSize = 2;
        // 自定义最大线程数
        int maximumPoolSize = 5;
        // 自定义线程存活时间
        long keepAliveTime = 60;
        TimeUnit unit = TimeUnit.SECONDS;
        // 创建自定义线程工厂，设置线程池名称
        ThreadFactory threadFactory = new NamedThreadFactory("MyScheduledThreadPool");
        // 创建 ScheduledThreadPoolExecutor 实例
        ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor(
                corePoolSize,
                threadFactory,
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        // 设置最大线程数
        scheduledExecutorService.setMaximumPoolSize(maximumPoolSize);
        // 设置线程存活时间
        scheduledExecutorService.setKeepAliveTime(keepAliveTime, unit);

        // 定义一个要执行的任务
        Runnable task = () -> {
            System.out.println(Thread.currentThread().getName() + " - Task executed at: " + System.currentTimeMillis()/1000);
        };
        // 延迟 2 秒后执行任务
        scheduledExecutorService.schedule(task, 2, TimeUnit.SECONDS);
        // 初始延迟 1 秒，然后每 3 秒执行一次任务
        scheduledExecutorService.scheduleAtFixedRate(task, 1, 3, TimeUnit.SECONDS);
        // 让主线程等待 30 秒，之后再执行关闭线程池的操作
        try {
            TimeUnit.SECONDS.sleep(30);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        // 关闭 ScheduledExecutorService
        try {
            scheduledExecutorService.shutdown();
            if (!scheduledExecutorService.awaitTermination(10, TimeUnit.SECONDS)) {
                scheduledExecutorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            scheduledExecutorService.shutdownNow();
        }
    }
}